<template>
  <div>
    <div class="pub-table-action-btn">
      <a-button v-if="!disabled" type="primary" icon="plus" @click="addMainMember">添加行</a-button>
      <ExcelImportButton icon="import" v-if="!disabled" v-btn-permission="'lu_008_imp_05'" class="ml20"
                         @handleSubmit="handleImport">导入
      </ExcelImportButton>
      <excel ref="exportAll" fileName="创新工作室主要成员" is-click-generate="false">
        <a-button icon="download" v-btn-permission="'lu_008_exp_06'" type="primary" class="ml20" slot="excelBtn"
                  @click="exportAll">导出全部
        </a-button>
      </excel>
      <export-mould
        style="margin-left: 5px"
        templateCode="创新工作室主要成员模板.xls"
        icon="cloud-download"
      ></export-mould>
    </div>

    <a-table
      :scroll="{x:1376}"
      ref="table"
      :pagination="false"
      :columns="mainMembersColumns"
      :data-source="pageTableData"
    >
      <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
      <template
        v-for="col in ['name','depName']"
        :slot="col"
        slot-scope="text, record, index">
        <template v-if="index === editingIndex">
          <ASelectOrgPeople
            v-if="col === 'name'"
            @onSelectChange="onSelectChange($event,index)"
            v-model="record['creatorId']"
            :select-people-name="record.name"
            :customRender="customRender"
            :init="true"
            style="width: 200px;"></ASelectOrgPeople>
          <SelectCompanyAndSubCompany
            v-else-if="col === 'depName'"
            @onSelectChange="record['depName'] = $event.name"
            v-model="record['depId']"
            style="width: 200px;"></SelectCompanyAndSubCompany>
          <template v-else>
            {{ text }}
          </template>
        </template>
        <template v-else>
          {{ text }}
        </template>
      </template>
      <template slot="operation" slot-scope="text, record, index">
        <div class="pub-table-list-action" v-if="!disabled">
          <template v-if="index === editingIndex">
            <span @click="save(index)">保存</span>
            <span @click="cancel(index)">取消</span>
          </template>
          <template v-if="editingIndex === null">
            <span @click="edit(index)">编辑</span>
            <span @click="del(record)">删除
                        </span>
          </template>
        </div>
      </template>
    </a-table>
    <pagination
      :total="tableData.length"
      v-model="pageNo"
      :pageSize.sync="pageSize"
      @change="handlePageChange"
      @showSizeChange="showSizeChange"
    ></pagination>
  </div>
</template>

<script>
import SelectOrgPeople from '@/components/Select/SelectOrgPeople.vue'
import SelectCompanyAndSubCompany from '@/components/Select/SelectCompanyAndSubCompany'
import ExcelImportButton from '@/components/ExcelImportButton' // excel导入按钮

import yiShiSanSaiApi from '@/api/union/yiShiSanSai'
import ExportMould from '@/components/ExportMould'
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople'

export default {
  name: 'mainMembers',
  props: {
    baseId: {
      type: String,
      default: ''
    },
    list: {
      type: Array,
      default: () => {
        return []
      }
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  components: {
    ASelectOrgPeople,
    SelectCompanyAndSubCompany,
    ExcelImportButton,
    ExportMould
  },
  data() {
    return {
      customRender: q => {
        let result = q.name
        if (q.postPNames && q.postPNames.length) {
          result = `${result} (${q.postPNames.join('/')}) `
        }
        return result
      },
      mainMembersColumns: [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          scopedSlots: { customRender: 'index' }
        },
        {
          title: '姓名',
          dataIndex: 'name',
          width: 100,
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '手机',
          dataIndex: 'phone',
          width: 120
        },
        {
          title: '性别',
          dataIndex: 'sex',
          width: 70
        }, {
          title: '出生年月',
          dataIndex: 'birthday',
          width: 120
        }, {
          title: '学历',
          dataIndex: 'education',
          width: 100
        }, {
          title: '职称',
          dataIndex: 'title',
          width: 100
        }, {
          title: '单位',
          dataIndex: 'depName',
          scopedSlots: { customRender: 'depName' },
          width: 200
        }, {
          title: '工作职务',
          dataIndex: 'jobDuty'
        }, {
          title: '操作',
          dataIndex: 'operation',
          width: 120,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      editingIndex: null,
      pageNo: 1,
      pageSize: 10,
      tableData: [],
      cacheTable: []
    }
  },
  watch: {
    list() {
      this.tableData = this.$clone(this.list)
    }
  },
  mounted() {
    this.$refs.exportAll.tableToExcelFile(this.$refs.table)
    this.tableData = this.$clone(this.list)
  },
  methods: {
    handlePageChange(pageNo, pageSize) {
      this.pageNo = pageNo
    },
    showSizeChange(pageNo, pageSize) {
      this.pageNo = 1
      this.pageSize = pageSize
    },
    exportAll() {
      if (this.tableData.length) {
        this.$refs.exportAll.setDataAndGenerate(this.tableData)
      } else {
        this.$message.warning('没有可导出的数据')
      }
    },
    async handleImport(e) {
      let newTable = []
      this.$console(e)
      e.map(row => {
        let temp = {}
        for (const rowKey in row) {
          let column = this.mainMembersColumns.find(columnRow => columnRow.title === rowKey)
          if (column) {
            let dataIndex = column.dataIndex
            temp[dataIndex] = row[rowKey]
          }
        }
        newTable.push(temp)
      })
      this.loading = true
      let res = await yiShiSanSaiApi.insertMainMember({ baseId: this.baseId, studioMainMemberDtos: newTable })
      this.loading = false
      this.$emit('refresh')
      // this.$notification.open({ message: '提示', duration: null, description: () => <pre>{res.message}</pre> })
      // console.log(newTable)
    },
    del(item) {
      this.$confirm({
        title: '确认删除该数据？',
        onOk: () => {
          let resIndex = this.tableData.findIndex(v => v.id === item.id)
          if (resIndex !== -1) {
            this.tableData.splice(resIndex, 1)
          }
          this.$emit('update:list', this.tableData)
          if (this.tableData.length && this.tableData.length <= (this.pageNo * this.pageSize - this.pageSize)) {
            this.pageNo = this.pageNo - 1
          }
        }
      })
    },
    onSelectChange(e, index) {
      this.tableData[index].sex = e.sex
      this.tableData[index].name = e.name
      this.tableData[index].creatorId = e.userId
      this.tableData[index].birthday = e.birthday
      this.tableData[index].education = e.specialitieMax
      this.tableData[index].title = e.jobTitle
      this.tableData[index].phone = e.phone
      this.tableData[index].jobDuty = e.jobTitle
      if (e.postPNames && e.postPNames.length) {
        this.tableData[index].jobDuty = e.postPNames.join('-')
      }
    },
    addMainMember() {
      if (this.editingIndex !== null) return this.$noticeWarning('请结束当前行再添加')
      this.cacheTable = this.$clone(this.tableData)
      this.tableData.unshift({
        id: Date.now(),
        sex: '',
        name: '',
        creatorId: '',
        birthday: '',
        education: '',
        title: '',
        jobDuty: '',
        phone: '',
        depName: '',
        depId: '',
        isAdd: true
      })
      this.editingIndex = 0
    },
    edit(index) {
      this.editingIndex = index
      this.cacheTable = this.$clone(this.tableData)
    },
    save(index) {
      if (!this.tableData[index].creatorId) return this.$noticeWarning('请选择人员')
      if (!this.tableData[index].depId) return this.$noticeWarning('请选择单位')
      if (this.tableData.find(v => {
        return v.creatorId === this.tableData[index].creatorId && v.id !== this.tableData[index].id
      })) {
        return this.$noticeWarning('请勿选择重复人员')
      }
      this.$emit('update:list', this.tableData)
      this.editingIndex = null
    },
    cancel(index) {
      this.tableData = this.$clone(this.cacheTable)
      this.$emit('update:list', this.cacheTable)
      this.editingIndex = null
    }
  },
  computed: {
    pageTableData() {
      return this.tableData.slice((this.pageNo - 1) * this.pageSize, this.pageNo * this.pageSize)
    }
  }
}
</script>

<style scoped>

</style>
